import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { list_assistant_metas, delete_assistant } from "@/api/assistant";
import { CODE } from "@/api/constants";
import { result } from "@/utils/result";

const useAssistantListStore = defineStore('assistant-list', () => {
    // 存meta列表
    // 维护当前活跃的助理
    const assistantMetas = ref([])
    const isEmptyData = computed(() => {
        return assistantMetas.value.length === 0
    })

    const activeAssistantId = ref("")
    const isSelectActiveAssistant = computed(() => {
        return !!activeAssistantId.value
    })
    const setActiveAssistant = (meta) => {
        activeAssistantId.value = meta.id
        repushMeta(meta)
    }

    const refreshAssistantMetas = async () => {
        assistantMetas.value = []
        activeAssistantId.value = ""

        const resp = await list_assistant_metas()
        if (resp.code != CODE.OK) {
            return result(false, resp.msg)
        }
        assistantMetas.value = resp.data.metas
        return result(true, "获取助理列表成功")
    }

    const pushMeta = (meta) => {
        assistantMetas.value.unshift(meta);
    }

    const deleteMeta = (meta) => {
        const index = assistantMetas.value.findIndex(item => item.id === meta.id);
        if (index !== -1) {
            assistantMetas.value.splice(index, 1);
        }
    }

    const repushMeta = (meta) => {
        deleteMeta(meta)
        pushMeta(meta)
    }

    const deleteAssistant = async (assistantId) => {
        const resp = await delete_assistant({assistantId})
        if (resp.code != CODE.OK) {
            return result(false, resp.msg)
        }
        deleteMeta(resp.data)
        if (activeAssistantId.value == resp.data.id) {
            activeAssistantId.value = ""
        }
        return result(true, "删除成功")
    }

    return { assistantMetas, isEmptyData, activeAssistantId, isSelectActiveAssistant, setActiveAssistant,
        refreshAssistantMetas, pushMeta, deleteMeta, repushMeta, deleteAssistant }
})

export default useAssistantListStore;